﻿using Mall.Service.Interfaces;
using Mall.Web.ViewModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace Mall.Web.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LonginController : BaseController
    {
        private readonly IShipperUserService _shipperUserService;
        private JwtOptions _jwtParametersOptions { get; }
        public LonginController(IShipperUserService shipperUserService, IOptions<JwtOptions> jwtParametersOptions)
        {
            _shipperUserService = shipperUserService;
            _jwtParametersOptions = jwtParametersOptions.Value;
        }

        [HttpPost("LoginMiniprogram")]
        [AllowAnonymous]
        public async Task<LoginResponse> LoginMiniprogram([FromBody] LoginVM vm)
        {
            var user=  await _shipperUserService.GetShipperUserByPhone(vm.phone, vm.name);

            var result = new LoginResponse();
            var timeNow = DateTime.Now;
            //生成JWT Token
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,"ccpshipperApp"),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Sid, user.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.Phone),
                new Claim(JwtRegisteredClaimNames.Iat, timeNow.Ticks.ToString(), ClaimValueTypes.Integer64),
            };

            var jwt = new JwtSecurityToken(
                                 issuer: _jwtParametersOptions.Issuer,
                                 audience: _jwtParametersOptions.Audience,
                                 claims: claims,
                                 notBefore: _jwtParametersOptions.NotBefore,
                                 expires: _jwtParametersOptions.Expiration,
                                 signingCredentials: _jwtParametersOptions.SigningKey
                          );

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            result.Id = user.Id; 
            result.Name = user.Name;
            result.Phone = user.Phone;
            result.Jwt = encodedJwt;
            return result;
        }
    }
}
